/*
 *
 *      Copyright (c) 2018-2099, lipengjun All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the fly2you.cn developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: lipengjun (939961241@qq.com)
 *
 */
package com.platform.handler;

import com.platform.modules.wx.entity.WxMsgEntity;
import com.platform.modules.wx.service.MsgReplyService;
import com.platform.modules.wx.service.WxMsgService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 微信公众号消息处理（消息处理）
 *
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    MsgReplyService msgReplyService;
    @Autowired
    WxMsgService wxMsgService;
    private static final String TRANSFER_CUSTOMER_SERVICE_KEY = "人工";
    private static final String WEN_DANG = "文档";

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String msgType = wxMessage.getMsgType();
        String textContent = wxMessage.getContent();
        String fromUser = wxMessage.getFromUser();
        String toUser = wxMessage.getToUser();
        if (WxConsts.XmlMsgType.TEXT.equals(msgType)) {
            if (StringUtils.equals(textContent, WEN_DANG)) {
                WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                item.setTitle("微同开源商城启动部署手册");
                item.setDescription("减少重复造轮子，开源微信小程序商城（前后端开源：uniapp+Java），拼团、秒杀、优惠券、积分购物、直播卖货、分销等功能。快速搭建一个属于自己的微信小程序商城。QQ交流群：66502035、870579539、151602347欢迎大家进群交流技术。");
                item.setPicUrl("https://mmbiz.qpic.cn/mmbiz_png/oTZyaRhiajfPGH1iaZomhzBW3ic0bJjIO62RKsBZUzS7SjGnhf47taRVrmBPFxsKsUjsHTow3PyOsCibtdpcT9iaWxg/640?wx_fmt=png");
                item.setUrl("https://mp.weixin.qq.com/s?__biz=Mzg4MTIzNjM2OQ==&mid=2247483900&idx=1&sn=9fe60f15044a0f4cd4c40bf9a39a0d1b&chksm=cf684102f81fc8148b789060de7d158f172e1ac6bdd8e0ff3edf8e1095a9fcf3dc959d4d5906#rd");
                return WxMpXmlOutMessage.NEWS().addArticle(item)
                        .fromUser(toUser).toUser(fromUser)
                        .build();
            }
        }
        String appid = WxMpConfigStorageHolder.get();
        boolean autoReplyed = msgReplyService.tryAutoReply(appid, false, fromUser, textContent);
        //当用户输入关键词如“人工”，并且有客服在线时，把消息转发给在线客服
        if (TRANSFER_CUSTOMER_SERVICE_KEY.equals(textContent) || !autoReplyed) {
            wxMsgService.addWxMsg(WxMsgEntity.buildOutMsg(WxConsts.KefuMsgType.TRANSFER_CUSTOMER_SERVICE, fromUser, null));
            return WxMpXmlOutMessage
                    .TRANSFER_CUSTOMER_SERVICE().fromUser(toUser)
                    .toUser(fromUser).build();
        }
        return null;
    }
}
